<template>
	<el-dialog
		title="导入名额"
		width="40%"
		custom-class="custom-dialog"
		:visible.sync="dialogVisible"
		@closed="handleClosed"
	>
		<div class="dialog-container">
			<el-alert
				v-if="state === 'success'"
				title="所有信息导入成功，可使用小程序进行报名！"
				type="success"
				:closable="false"
			/>
			<el-row type="flex" align="middle" justify="space-between" class="step-box">
				<div style="line-height: 34px">1、请先下载模板，进行导入信息填写</div>
				<el-button size="small" icon="el-icon-download" @click="handleDownload">模版下载</el-button>
			</el-row>
			<div class="step-box step-one">
				<div class="step-tip">2、导入信息填写完成后，请按规定格式，大小上传附件文件</div>
				<el-upload
					ref="upload"
					v-loading="loading"
					class="upload-demo"
					drag
					:file-list="fileList"
					action="#"
					:auto-upload="false"
					:show-file-list="false"
					:on-change="beforeUpload"
					:http-request="handleHttpRequest"
				>
					<div v-if="file" class="el-upload__tip">{{ file.name }}</div>
					<div class="el-upload__text">
						将文件拖到此处，或
						<em v-if="!file">点击上传</em>
						<em v-else>点击重新上传</em>
					</div>
					<div slot="tip" class="el-upload__tip">
						<span>支持上传文件为：xlsx、xls(大小在10M以内)</span>
					</div>
				</el-upload>
			</div>
			<el-form
				ref="forms"
				size="small"
				:model="forms"
				:rules="rules"
				label-width="autp"
				class="custom-form"
			>
				<el-form-item label="赛事分组：" prop="group_id">
					<el-radio-group v-model="forms.group_id">
						<el-radio :label="item.group_id" v-for="item in groupData" :key="item.group_id">
							{{ item.group_name }}
						</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="名额类型：" prop="is_free" style="margin-bottom: 0">
					<el-radio-group v-model="forms.is_free">
						<el-radio :label="1">免费名额</el-radio>
						<el-radio :label="0">折扣名额</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
		</div>
		<div slot="footer" class="dialog-footer">
			<el-button size="small" @click="dialogVisible = false">取 消</el-button>
			<el-button :loading="loading" size="small" type="primary" @click="handleConfirm">
				确 定
			</el-button>
		</div>
	</el-dialog>
</template>

<script>
	import { importPlayer } from '@/api/user-manager.js'
	import { getInfo } from '@/api/competition-manage.js'
	export default {
		data() {
			return {
				loading: false,
				state: '', // 上传状态
				file: null,
				tableError: [],
				dialogVisible: false,
				info: {},
				forms: {
					group_id: '',
					is_free: 0 //是否免费0否1是
				},
				rules: {
					group_id: [{ required: true, message: '请选择分组', trigger: 'change' }],
					is_free: [{ required: true, message: '请选择', trigger: 'change' }]
				},
				groupData: [],
				fileList: []
			}
		},
		methods: {
			init(info) {
				console.log(info)
				this.info = info
				this.forms = {
					group_id: '',
					is_free: 0 //是否免费0否1是
				}
				this.getDetailInfo(info.race_id)
				this.dialogVisible = true
			},
			async getDetailInfo(race_id) {
				const loading = this.$setLoading()
				try {
					const { data } = await getInfo({ race_id })
					this.groupData = data.groups

					loading.close()
				} catch (e) {
					loading.close()
					console.log(e)
				}
			},
			handleClosed() {
				this.state = ''
				this.tableError = []
				this.ids = undefined
				this.file && (this.$refs.upload.clearFiles(), (this.file = null))
			},
			// 下在模板
			handleDownload() {
				const url = 'https://api.mls.xinzi365.com/uploads/templates/sponsor.xlsx'
				const fileName = '导入名额信息模板'
				if (window.navigator && window.navigator.msSaveOrOpenBlob) {
					this.$http({
						method: 'post',
						url: url,
						responseType: 'blob',
						headers: {
							'content-type': 'application/vnd.ms-excel'
						}
					}).then(res => {
						if (res.status !== 200) {
							this.$message({
								message: '下载失败！',
								type: 'error',
								duration: 1.5 * 1000
							})
							return
						}
						var csvData = new Blob([res.data], {
							type: 'application/vnd.ms-excel;charset=utf-8'
						})
						window.navigator.msSaveOrOpenBlob(csvData, fileName)
					})
				} else {
					var a = document.createElement('a')
					document.body.appendChild(a)
					a.style = 'display: none'
					a.href = url
					a.download = fileName
					a.click()
					a.remove()
					window.URL.revokeObjectURL(url)
				}
			},
			// 上传模板
			handleHttpRequest(config) {
				const formData = new FormData()
				formData.append('file', config.file)
				formData.append('race_id', this.info.race_id)
				formData.append('spon_id', this.info.spon_id)
				formData.append('group_id', this.forms.group_id)
				formData.append('is_free', this.forms.is_free)
				this.loading = true
				const loading = this.$setLoading({ text: '文件上传中~' })
				importPlayer(formData).then(
					res => {
						console.log(res)
						this.loading = false
						loading.close()
						this.dialogVisible = false
						this.$alert(res.msg, '提示', {
							confirmButtonText: '知道了',
							confirmButtonClass: 'primary-btn',
							callback: action => {
								console.log(action)
							}
						})
						this.file = null
						this.fileList = []
						this.state = 'success'
					},
					err => {
						console.log(err)
						loading.close()
						this.file = null
						this.fileList = []
						this.loading = false
					}
				)
			},
			beforeUpload(file) {
				const fileName = file.name
				const suffix = fileName.substring(fileName.lastIndexOf('.') + 1)
				const isExcel = suffix === 'xls' || suffix === 'xlsx'
				if (!isExcel) {
					this.$message.warning('上传格式错误，请重新上传')
				}
				this.file = file
				return isExcel
			},
			handleConfirm() {
				this.$refs.forms.validate(async valid => {
					if (valid) {
						if (!this.file) {
							this.$message.error('请上传文件！')
							return
						}
						this.$refs.upload.submit()
					} else {
						this.$message.warning('请完善信息后提交！')
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep {
		.custom-dialog {
			border-radius: 10px;
			.el-dialog__header {
				border-bottom: 1px solid #eeeeee;
				padding-bottom: 10px;
			}
			.el-dialog__title {
				font-size: 14px;
				margin-top: 5px;
				display: block;
			}
			.el-dialog__body {
				padding: 15px 24px 0;
				max-height: 500px;
				overflow-y: auto;
			}
			.el-dialog__footer {
				padding-top: 10px;
			}
			.dialog-footer {
				display: flex;
				justify-content: end;
			}
		}
		.upload-demo {
			width: 100%;
			.el-upload,
			.el-upload-dragger {
				width: 100%;
			}
			.el-upload-dragger {
				height: 120px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
			}
			.el-upload__tip {
				color: rgba(0, 0, 0, 0.45);
				font-size: 12px;
				display: flex;
				align-items: center;
				.rules {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-left: 10px;
					cursor: pointer;
				}
			}
			.el-upload__text {
				font-size: 14px;
				margin-top: 12px;
			}
		}
		.el-alert {
			margin-bottom: 18px;
		}
	}
	.step-box {
		padding: 12px 20px;
		border-radius: 4px;
		background-color: #f7f7f7;
		border: 1px solid #d9d9d9;
		margin-bottom: 16px;
		&.batch {
			padding: 0;
			margin: 0;
			border: 0;
			background-color: #ffffff;
		}
	}
	.step-tip {
		font-size: 14px;
		margin-bottom: 12px;
		line-height: 22px;
		color: rgba(0, 0, 0, 0.65);
	}
	.upload-box {
		border: 1px dashed #d9d9d9;
		background-color: #ffffff;
		border-radius: 4px;
	}
	.tips {
		display: flex;
		align-items: center;
		margin-bottom: 6px;
		span {
			color: #333333;
			font-size: 12px;
			font-weight: bold;
			margin-left: 4px;
		}
	}
</style>
